package com.fyp.speachrecognition;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.StringTokenizer;

import com.fyp.MediaPlayer.MediaPlayerLibrary;
import com.fyp.settings.FileNames;
import com.fyp.settings.SettingsMain;
import com.fyp.speachrecognition.SpeechDialer.PhoneCallListener;

import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.PhoneLookup;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.speech.RecognizerIntent;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;

public class DeleteContactActivity extends Activity implements OnInitListener{

	 MediaPlayer mrL = null;
	 private ListView wordList;
	 private static final int VR_REQUEST = 909;
	 String Dial="tel:";
	 private final String LOG_TAG = "Speech Dialer";
	 boolean flag=true;
	 int NAME=1,NUMBER=2,DELETE=3,CALL=4,CALLWITHNAME=5;
	 int action=0;
	 String name="", number="";
	 private int MY_DATA_CHECK_CODE = 0;
	 private TextToSpeech myTTS;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_delete_contact);
		Intent i=this.getIntent();
		Bundle b=i.getExtras();
		
		if(!((Boolean) b.get("Login_success")))
		{
			finish();
		}
		else
		{
			mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.phn_book_recrd_menu);
			 Button speechBtn = (Button) findViewById(R.id.DelContactSpeakBtn);
			    wordList = (ListView) findViewById(R.id.deleteContactList);
			    PhoneCallListener phoneListener = new PhoneCallListener();
				TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
				telephonyManager.listen(phoneListener,PhoneStateListener.LISTEN_CALL_STATE);
			    
			      
			   /* ArrayAdapter<String > arrayAdapter = new ArrayAdapter<String> (this, R.layout.word, getContactList());
			    
			    wordList.setAdapter(arrayAdapter);*/
				speechBtn.setOnClickListener(new OnClickListener()
		        {
					public void onClick(View v) 
					{
						if(MediaPlayerLibrary.isPlaying())
						{
							mrL.stop();
							mrL.release();
							MediaPlayerLibrary.setPlaying(false);
						}
						 
						Intent listenIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
			        	listenIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE, getClass().getPackage().getName());
			        	listenIntent.putExtra(RecognizerIntent.EXTRA_PROMPT, "Say a word!");
			        	listenIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
			        	listenIntent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS, 10);
			            startActivityForResult(listenIntent, VR_REQUEST);
					}
		        	
		        });
				
				Intent checkTTSIntent = new Intent();
		    	checkTTSIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
		    	startActivityForResult(checkTTSIntent, MY_DATA_CHECK_CODE);
		}
		
		
	}
	public List<String> getContactList()
	{
		ArrayList <String> contactList = new ArrayList<String>();

		// Uri contactUri = ContactsContract.Contacts.CONTENT_URI;
		String[] PROJECTION = new String[] {
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME,
            ContactsContract.Contacts.HAS_PHONE_NUMBER,
    };
    String SELECTION = ContactsContract.Contacts.HAS_PHONE_NUMBER + "='1'";
    Cursor contacts = getContentResolver().query(ContactsContract.Contacts.CONTENT_URI, PROJECTION, SELECTION, null, null);
    try
    {

    if (contacts.getCount() > 0)
    {
        while(contacts.moveToNext()) 
        {
            Person aContact = new Person();
         //   int idFieldColumnIndex = 0;
            int nameFieldColumnIndex = 0;
            int numberFieldColumnIndex = 0;

            String contactId = contacts.getString(contacts.getColumnIndex(ContactsContract.Contacts._ID));

            nameFieldColumnIndex = contacts.getColumnIndex(PhoneLookup.DISPLAY_NAME);
            if (nameFieldColumnIndex > -1)
            {
                aContact.setName(contacts.getString(nameFieldColumnIndex));
            }

            PROJECTION = new String[] {Phone.NUMBER};
            final Cursor phone = managedQuery(Phone.CONTENT_URI, PROJECTION, Data.CONTACT_ID + "=?", new String[]{String.valueOf(contactId)}, null);
            try
            {
            if(phone.moveToFirst()) 
            {
                while(!phone.isAfterLast())
                {
                    numberFieldColumnIndex = phone.getColumnIndex(Phone.NUMBER);
                    if (numberFieldColumnIndex > -1)
                    {
                        aContact.setPhoneNum(phone.getString(numberFieldColumnIndex));
                        phone.moveToNext();
                        TelephonyManager mTelephonyMgr;
                        mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
                        if (!mTelephonyMgr.getLine1Number().contains(aContact.getPhoneNum()))
                        {
                            contactList.add(aContact.getName()+" "+aContact.getPhoneNum());  
                        }
                    }
                }
            }
            }catch(Exception e)
            {
            	e.printStackTrace();
            }
            finally
            {
            phone.close();
            }
        }
    }
    }catch(Exception e)
    {
    	e.printStackTrace();
    }
    finally
    {
        contacts.close();
    }

    return contactList;
}
	private class Person {
	    String myName = "";
	    String myNumber = "";

	    public String getName() {
	        return myName;
	    }

	    public void setName(String name) {
	        myName = name;
	    }

	    public String getPhoneNum() {
	        return myNumber;
	    }

	    public void setPhoneNum(String number) {
	        myNumber = number;
	    }
	}
	/*private void contactList()
	{
		ContentResolver cr = getContentResolver();
	    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
	            null, null, null, null);

        ArrayList<String> suggestedWords = new ArrayList<String>();
	   try
	   {
	    if (cur.moveToFirst()) 
        {
            do 
            {
            	suggestedWords.add(
                cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)) + " "+
                cur.getString(cur.getColumnIndex(PhoneLookup.NUMBER)));
     	       
            }
        
	    while (cur.moveToNext()); 
        }
	   }
	        catch(Exception e)
	        {
	            System.out.println(e.getStackTrace());
	        }
	    finally
	    {
	    	}
	}*/
	public static boolean deleteContact(Context ctx, String phone, String name) 
	{
	    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(phone));
	    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
	    try {
	        if (cur.moveToFirst()) 
	        {
	            do 
	            {
	                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(name)) 
	                {
	                    String lookupKey = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.LOOKUP_KEY));
	                    Uri uri = Uri.withAppendedPath(ContactsContract.Contacts.CONTENT_LOOKUP_URI, lookupKey);
	                    ctx.getContentResolver().delete(uri, null, null);
	                    return true;
	                }

	            } while (cur.moveToNext());
	        }

	    } catch (Exception e) {
	        System.out.println(e.getStackTrace());
	    }
	    return false;
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		  action=0;
		  String wordChosen = null;
		  if (requestCode == MY_DATA_CHECK_CODE) {
		        if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
		            myTTS = new TextToSpeech(this, this);
		        }
		        else {
		            Intent installTTSIntent = new Intent();
		            installTTSIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
		            startActivity(installTTSIntent);
		        }
		}
	    if (requestCode == VR_REQUEST && resultCode == RESULT_OK) 
	    {
	        ArrayList<String> suggestedWords = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
	        wordList.setAdapter(new ArrayAdapter<String>(this, R.layout.word,suggestedWords));
	       ListIterator<String> it = suggestedWords.listIterator();
	        while(it.hasNext())
	        {
	        	wordChosen = it.next();
	        	Log.v(LOG_TAG, "auto word chosen: "+wordChosen);
	        	wordChosen.trim();
	        	String s = wordChosen;
	        	wordChosen=constructString(wordChosen.toLowerCase());
	        	if(getName().length()==0&&(!wordChosen.contains("del")||!wordChosen.contains("delete")||!wordChosen.contains("call")||!wordChosen.contains("dial")))
	        	{
	        		Log.v(LOG_TAG, "Name: "+wordChosen);
	            		action=NAME;
	            		flag=false;
	            	
	        	}
	        	else if((wordChosen.equalsIgnoreCase("call")||wordChosen.equals("DIAL")&&( getName().length()!=0 && getNumber().length()==0)))
	        	{
	        		Log.v(LOG_TAG, "CALL with name: "+wordChosen);
	        		flag=false;
            		action=CALLWITHNAME;
	        	}
	        	else if(wordChosen.equalsIgnoreCase("clear")||wordChosen.equals("remove"))
	        	{
	        		Log.v(LOG_TAG, "Clear: "+wordChosen);
	        		flag=false;
            		action=101;
	        	}
	        	else if(getName().length()!=0 &&getNumber().length()==0&& (!wordChosen.contains("del")||!wordChosen.contains("delete")||!wordChosen.contains("call")||!wordChosen.contains("dial")||!wordChosen.contains("remove")))
	        	{
	        		
	        		if(isInteger(wordChosen))
            		{
	        			Log.v(LOG_TAG, "Number: "+wordChosen);
	        			action=NUMBER;
            			flag=false;            			
            		}
	        		else if(wordChosen.equalsIgnoreCase("clear")||wordChosen.equals("remove"))
		        	{
		        		Log.v(LOG_TAG, "Clear: "+wordChosen);
		        		flag=false;
	            		action=101;
		        	}
            		else
            		{
            			Log.v(LOG_TAG, "Token (Error Block where No not found): "+wordChosen);
            			flag=true;
            			action=0;            		
            		}
	            	
	        	}
	        	else if((wordChosen.equals("del")||wordChosen.equals("delete")&&( getName().length()!=0 && getNumber().length()!=0)))
	        	{
	        		Log.v(LOG_TAG, "DELETE: "+wordChosen);
	        		flag=false;
            		action=DELETE;
	        	}
	        	else if((wordChosen.equalsIgnoreCase("call")||wordChosen.equals("DIAL")&&( getName().length()!=0 && getNumber().length()!=0)))
	        	{
	        		Log.v(LOG_TAG, "CALL: "+wordChosen);
	        		flag=false;
            		action=CALL;
	        	}
	        	
	        	else
	        	{
	        		flag=true;
	        	}
	        	
	        
	        	 
	        	if(!flag)
	        	{
	        		break;
	        	}
	        	
	        	
	        }
	    
	    if(action==NAME)
	    {
	    	setName(wordChosen);
	    	mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.recrd_number_save);
	    }
	    else if(action==NUMBER)
	    {
	    	setNumber(wordChosen);
	    	
	    }
	    else if(action==DELETE)
	        {
	        	Log.v(LOG_TAG, getNumber()+" "+getNumber());
	        	if(deleteContact(this,getNumber(),getName()))
	        	{
	        		mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.delete_success);
	        	}
	        	
	        	else
	        	{
	        		mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.num_not_delete);
	        	}
	        	setName("");
	        	setNumber("");
	        }
	    else if (action == CALL)
	    {
	    	if(getAndCheckNumberFromContactList(this,getName(),getNumber()))
	    	{
	    	
	    				Dial="tel:"+getNumber();
	    			
	    		
	    		
	    		
	    			setName("");
		        	setNumber("");
	    			Intent callIntent = new Intent(Intent.ACTION_CALL);
	    			callIntent.setData(Uri.parse(Dial));Dial="tel:";
		    		
		        	startActivity(callIntent);
	    		
	    		
	    		
	    	}
	    	else
	    	{
	    		mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.nuber_not_found);
	    	}
	    }
	    else if(action == CALLWITHNAME)
	    {
	    	String num=getNumber(getName());
	    	Log.v(LOG_TAG, "Number: "+num);
	    	if(num.length()==0)
	    		
	    	{
	    		mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.nuber_not_found);
	    		
	    	}
	    	else
	    	{
	    		Dial="tel:"+num;
	    		setName("");
	        	setNumber("");
    			Intent callIntent = new Intent(Intent.ACTION_CALL);
    			callIntent.setData(Uri.parse(Dial));Dial="tel:";
	    		
	        	startActivity(callIntent);
	    		
	    	}
	    }
	    else if(action == 101)
    	{
	    	setName("");
	    	Toast.makeText(this, "Cleared", Toast.LENGTH_SHORT).show();
        	setNumber("");
    	}
	        else if(action==0)
	        {
	        	mrL= MediaPlayerLibrary.startPlayingFromRaw(this, R.raw.no_keyword_match);
				setName("");
	        	setNumber("");
	        	Toast.makeText(this, "No Key Word Matches", Toast.LENGTH_SHORT).show();
	        }
	        
	    }
	    
	  
	    super.onActivityResult(requestCode, resultCode, data);
	}
	public boolean getAndCheckNumberFromContactList(Context ctx,String Name,String No) 
	{
		Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(No));
	    Cursor cur = ctx.getContentResolver().query(contactUri, null, null, null, null);
	    try {
	        if (cur.moveToFirst()) 
	        {
	            do 
	            {
	                if (cur.getString(cur.getColumnIndex(PhoneLookup.DISPLAY_NAME)).equalsIgnoreCase(Name)) 
	                {
	                    return true;
	                }

	            } while (cur.moveToNext());
	        }

	    } catch (Exception e) {
	        System.out.println(e.getStackTrace());
	    }
	    return false;
	}
	public String getNumber(String Name)
	{
		String phoneNum="";
		ContentResolver cr = getContentResolver();
		Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null,null, null,ContactsContract.Contacts.DISPLAY_NAME);
		int kisiSayisi =  cur.getCount();

		if(kisiSayisi > 0)
		{
		    int KisiIndex = 0;
		    while(cur.moveToNext())
		    {
		        String id = cur.getString(cur.getColumnIndex(BaseColumns._ID));
		        String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
		        
		        if( (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0)&&name.equals(Name))
		        {
		            Cursor pCur = cr.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI,null,ContactsContract.CommonDataKinds.Phone.CONTACT_ID+ " = ?", new String[] { id }, null);
		            while (pCur.moveToNext())
		            {
		                phoneNum = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DATA));
		                 //String phoneType = pCur.getString(pCur.getColumnIndex(ContactsContract.CommonDataKinds.Phone.TYPE));
		                 /*String dogruGSM = gsmNoKontrol(phone);
		                 if(dogruGSM.compareTo("0") != 0){
		                        Kisi kisi = new Kisi(KisiIndex, name, dogruGSM, false);
		                        MyList.add(kisi);
		                        KisiIndex ++;
		                 }*/
		             }
		             pCur.close();
		         }
		     }
		 }
		cur.close();
		return phoneNum;
	}
	private String constructString(String wordChosen) {
		// TODO Auto-generated method stub
		StringBuilder sb = new StringBuilder();
		String[] s=wordChosen.split("[ ]");
		int i=0;
    	
			while (i<s.length)
			{
				sb.append(s[i]);
				i++;
			}
		
		
		return sb.toString().trim();
	}
	public static boolean isInteger(String s) 
	{
	    try { 
	        Integer.parseInt(s); 
	    } catch(NumberFormatException e) { 
	        return false; 
	    }
	    // only got here if we didn't return false
	    return true;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
	    MenuInflater inflater = getMenuInflater();
	    inflater.inflate(R.menu.menu, menu);
	    return true;
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
	    // Handle item selection
	    switch (item.getItemId()) {
	        case R.id.Configuration:
	            record();
	            return true;
	        default:
	            return super.onOptionsItemSelected(item);
	    }
	}

	private void record() {
		// TODO Auto-generated method stub
		Intent i = new Intent(getApplicationContext(), SettingsMain.class);
		startActivity(i);
	}
	//==================
	public class PhoneCallListener extends PhoneStateListener {
		 
		private boolean isPhoneCalling = false;
	
		String LOG_TAG = "LOGGING 123";
	
		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
	
			if (TelephonyManager.CALL_STATE_RINGING == state) {
				// phone ringing
				Log.i(LOG_TAG, "RINGING, number: " + incomingNumber);
			}
	
			if (TelephonyManager.CALL_STATE_OFFHOOK == state) {
				// active
				Log.i(LOG_TAG, "OFFHOOK");
	
				isPhoneCalling = true;
			}
	
			if (TelephonyManager.CALL_STATE_IDLE == state) {
				// run when class initial and phone call ended, 
				// need detect flag from CALL_STATE_OFFHOOK
				Log.i(LOG_TAG, "IDLE");
	
				if (isPhoneCalling) {
	
					Log.i(LOG_TAG, "restart app");
	
					Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName());
					i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(i);
	
					isPhoneCalling = false;
				}
	
			}
		}
	}
	
	//=================
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getNumber() {
		return number;
	}
	public void setNumber(String number) {
		this.number = number;
	}
	public void onInit(int initStatus) {
	    if (initStatus == TextToSpeech.SUCCESS) {
	        myTTS.setLanguage(Locale.UK);
	    }
	    else if (initStatus == TextToSpeech.ERROR) {
	        Toast.makeText(this, "Sorry! Text To Speech failed...", Toast.LENGTH_LONG).show();
	    }
	}
	@Override
	  protected void onResume() {
		
	    super.onResume();
	   
	  }

	  @Override
	  protected void onPause() {
		 
	    super.onPause();
	   
	    
	  }
	  protected void onDestroy()
	  {
		 myTTS.stop();
		  myTTS.shutdown();
		  super.onDestroy();
		  
	  }
	
}
